package order.action;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import order.model.OpenTable;
import order.service.IOrderService;

import common.action.BaseAction;
import common.bean.PageInfo;
import common.exception.BusinessException;
/**
 * 订单管理: 订单列表、订单管理
 * @author 肖波
 *
 */
public class OrderAction extends BaseAction
{
	private static final long serialVersionUID = 9087890202612005277L;

	private IOrderService orderService;
	private ObjectMapper jsonMapper;
	
	//买单
	public String payTheBill()
	{
		return SUCCESS;
	}
	
	//罗列订单
	public String listOrders()
	{
		List<OpenTable> openTables = null;
		PageInfo page = buildPageInfo();
		try
		{
			openTables = orderService.queryOpenTables(page);
		} catch (BusinessException e)
		{
			log.error(e);
		}
		
		try
		{
			this.sendClientJSON(openTablsAsStr(openTables));
		} catch (IOException e)
		{
			log.error(e);
		}
		
		return null;
	}
	
	private PageInfo buildPageInfo()
	{
		PageInfo page = new PageInfo();
		if(StringUtils.isNotBlank(this.getParameter("index"))
				&& StringUtils.isNotBlank(this.getParameter("count")))
		{
			page.setIndex(Long.parseLong(getParameter("index")));
			page.setCount(Long.parseLong(getParameter("count")));
		}
		else
		{
			page.setIndex(1L);
			page.setCount(3L);
		}
		return page;
	}
	
	private String openTablsAsStr(List<OpenTable> openTables)
	{
		try
		{
			if(openTables != null)
			return jsonMapper.writeValueAsString(openTables);
		}
		catch(Exception e)
		{
			log.error(e);
		}
		
		return "[]";
	}

	public IOrderService getOrderService()
	{
		return orderService;
	}

	public void setOrderService(IOrderService orderService)
	{
		this.orderService = orderService;
	}

	public ObjectMapper getJsonMapper()
	{
		return jsonMapper;
	}

	public void setJsonMapper(ObjectMapper jsonMapper)
	{
		this.jsonMapper = jsonMapper;
	}
}
